﻿/**
 * @name:  表格增强插件(拖拽列)
 **/
layui.define(['table', 'form', 'timemsg'], function (exports) {
	var $ = layui.$,
		table = layui.table,
		form = layui.form,
		timemsg = layui.timemsg,
		HIDE = 'layui-hide',
		isNoCache
	// 封装方法
	var mod = {
		render: function (myTable) {
			var _this = this
			getAccountId() //确保top.layui.AccountId存在
			var ID = !!myTable.id ? '#' + myTable.id : myTable.elem
			isNoCache = myTable.isNoCache
			if (!layui[ID]) {
				// 排除所有页面中不需要显示给用户的列
				_this.exclude(myTable, myTable.excludeData)
				layui[ID] = true
				//添加清除缓存图标
				if (!isNoCache) {
					myTable.defaultToolbar = $.merge(myTable.defaultToolbar, [
						{
							title: '保存个性化设置',
							layEvent: 'uploadTableCache',
							icon: 'layui-icon-upload-drag'
						},
						{
							title: '下载个性化设置',
							layEvent: 'downTableCache',
							icon: 'layui-icon-download-circle'
						},
						{
							title: '清除列表个性化', //标题
							layEvent: 'clearTableCache', //事件名，用于 toolbar 事件中使用
							icon: 'layui-icon-template' //图标类名
						}
					])
				}
				var tableCache = this.deepParse(localStorage.getItem(location.pathname + myTable.elem))
				if (!isNoCache && !!tableCache.cols && myTable.cols[0].length == tableCache.cols[0].length) {
					//判断简单列的长度和本地保存的是否相同,相同则使用缓存列排序
					myTable.cols = tableCache.cols
					!tableCache.initSort || (myTable.initSort = tableCache.initSort)
					!tableCache.limit || (myTable.limit = tableCache.limit) // 每页的数量
				}

				loadmyAccountDefault()
				function loadmyAccountDefault() {
					//高级搜索默认值存在时，只加载高级搜索默认值
					if (!top.layui.AccountDefault || myTable.NoExsearchDefault) {
						return
					}
					var advTableUrl = location.pathname + ':adv_search_form',
						myAccountDefault = top.layui.AccountDefault[advTableUrl],
						$advForm = $('form#adv_search_form')
					if (!myAccountDefault || Object.keys(myAccountDefault).length === 0 || $advForm.length === 0 || !layui.advanceSearchUrl) return
					myTable.url = layui.advanceSearchUrl
					var conditions = []

					if (layui.advance) {
						conditions = $.extend(true, {}, myAccountDefault)
						if (conditions['data']) conditions['data'] = JSON.parse(conditions['data']) //tapd版高级搜索 默认值加载 data 需要 parse
					} else {
						$.each(myAccountDefault, function (i, item) {
							var index = i.indexOf('Compute')
							if (index == -1) {
								return
							}
							var id = i.slice(0, index),
								condition = $advForm
									.find('#' + id)
									.closest('.adv-search-item')
									.find('.adv-search-condition')
									.data('condition')
							conditions.push({ Condition: condition, ComputeSign: item, LinkSign: 'and', LeftSign: '', ConditionValue: myAccountDefault[id], RightSign: '' })
						})
					}

					myTable.where.query = JSON.stringify(conditions)
					setTimeout(function () {
						delete myTable.where.query
					}, 3000)
					myTable.query = null
				}

				table.render(myTable)

				var $tableDiv = $('[lay-id="' + ID.replace('#', '') + '"] table')
				//手机端时 css 隐藏 number、radio 列
				var css = '@media screen and (max-width: 450px) { [data-key="' + $tableDiv.find('.laytable-cell-radio').parent().data('key') + '"], [data-key="' + $tableDiv.find('.laytable-cell-numbers').parent().data('key') + '"] { display: none; }}'

				if (myTable.showDetails === 'all') {
					//允许显示所有列详情
					css += 'body td[data-field] .layui-table-grid-down{display:block}'
				} else if ($.type(myTable.showDetails) === 'array') {
					//允许显示数组内列详情
					myTable.showDetails.forEach(function (field, i) {
						css += (i === 0 ? '' : ', ') + 'td[data-field="' + field + '"] .layui-table-grid-down'
					})
					css += '{display:block}'
				}
				addStyle(css)

				if (!$(frameElement).parent().hasClass('layadmin-tabsbody-item')) {
					colsHeight() //筛选列图标 iframe内点击调节高度
				}
			} else {
				if (typeof myTable.drag === 'undefined' || myTable.drag) {
					this.drag(myTable)
					this.toolCols(myTable)
					this.initSort(myTable)
					this.toolsDisplay(myTable)
					addNewButton(myTable)
				}
				//toolbar事件
				table.on('toolbar(' + myTable.id + ')', function (obj) {
					var event = obj.event
					_this[event] ? _this[event].call(this, obj, _this, myTable) : ''
				})
			}
		},
		/**
		 * 左右拖拽调整列顺序、向上拖隐藏列
		 * @param myTable
		 */
		drag: function (myTable) {
			if (myTable.cols.length > 1) {
				// 如果是复杂表头，则自动禁用拖动效果
				return
			}
			var _this = this,
				$table = $(myTable.elem),
				$tableBox = $table.next().children('.layui-table-box'),
				$tableHead = $.merge($tableBox.children('.layui-table-header').children('table'), $tableBox.children('.layui-table-fixed').children('.layui-table-header').children('table')),
				$fixedBody = $tableBox.children('.layui-table-fixed').children('.layui-table-body').children('table'),
				$noFixedBody = $tableBox.children('.layui-table-body').children('table'),
				$tableBody = $.merge($tableBox.children('.layui-table-body').children('table'), $fixedBody), //此处不能引用 $noFixedBody ，因为 $noFixedBody 将被修改
				$totalTable = $table.next().children('.layui-table-total').children('table'),
				$fixedTotalTable = $table.next().children('.layui-table-total').children('table.layui-table-total-fixed'),
				$noFixedTotalTable = $table.next().children('.layui-table-total').children('table:eq(0)'),
				tableId = myTable.id,
				isNoHide = myTable.isNoHide,
				colsWidthArr = [], //列的宽度数组, 用于计算自动滚动条时计算透明 th 位置
				fixedWidth = 0, //固定列总宽度
				isSimple = true, // 是否为简易拖拽
				toolbar = false, // 是否开启工具栏(用于拖动至固定列)
				isDraging = false,
				isStart = false

			if (!$tableHead.attr('drag')) {
				$tableHead.attr('drag', true)
				if (toolbar) {
					//$tableBox.append('<div class="soul-drag-bar"><div data-type="left">左固定</div><div data-type="none">不固定</div><div data-type="right">右固定</div></div>')
					//var $dragBar = $tableBox.children('.soul-drag-bar');
					//$dragBar.children('div').on('mouseenter', function () {
					//    $(this).addClass('active')
					//}).on('mouseleave', function () {
					//    $(this).removeClass('active')
					//})
				}

				$tableHead.find('th').each(function () {
					var $this = $(this),
						field = $this.data('field'),
						key = $this.data('key')
					if (!key) {
						return
					}

					var keyArray = key.split('-'),
						curColumn = myTable.cols[keyArray[1]][keyArray[2]],
						curKey = keyArray[1] + '-' + keyArray[2],
						isInFixed = $this.parents('.layui-table-fixed').length > 0,
						tableLx,
						tableRx

					if (!isInFixed) {
						if (!!curColumn.fixed) {
							fixedWidth += $this.width()
						} else {
							colsWidthArr.push({ thElem: $this, width: $this.width(), curColumn: curColumn })
						}
					}

					// 绑定鼠标按下事件
					$(this)
						.find('span:first,.laytable-cell-checkbox')
						.css('cursor', 'move')
						.on('mousedown', function (e) {
							if (e.button !== 0) {
								return
							}
							e.preventDefault()
							var $cloneHead = $this.clone().css('visibility', 'hidden'),
								originLeft = $this.position().left,
								originTop = $this.offset().top,
								disX = e.clientX - originLeft, // 鼠标距离被移动元素左侧的距离
								color = $this.parents('tr:eq(0)').css('background-color'),
								width = $this.width(),
								moveDistince = 0,
								$that = $(this),
								isFixed = curColumn.fixed,
								lastClientX = -1
							isStart = true
							//区分click、drag事件

							// 阻止文本选中
							$(document).bind('selectstart', function () {
								return false
							})

							fixedWidth = 0
							for (var i = 0, colsLength = myTable.cols[0].length; i < colsLength; i++) {
								//重置固定列总宽度
								if (!myTable.cols[0][i].fixed) break
								if (!myTable.cols[0][i].width) {
									fixedWidth += $tableHead.find('th[data-key="' + myTable.cols[0][i].key + '"]').width()
								} else {
									fixedWidth += Number(myTable.cols[0][i].width)
								}
							}

							// 移动事件
							$('body')
								.on('mousemove', function (e) {
									if (isStart && $cloneHead) {
										$tableBox.removeClass('no-left-border')
										if (!isDraging) {
											if (toolbar) {
												$dragBar.attr('data-type', isFixed || 'none')
												$dragBar.addClass('active')
											}

											$this.after($cloneHead)
											$this.addClass('isDrag').css({
												position: 'absolute',
												'z-index': 1,
												'border-left': '1px solid #e6e6e6',
												'background-color': color,
												width: width + 1
											})

											if (isSimple) {
												//设置蒙板
											} else {
												//(isInFixed ? $fixedBody : $tableBody).find('td[data-key="' + key + '"]').each(function () {
												//    $(this).after($(this).clone().css('visibility', 'hidden').attr('data-clone', ''));
												//    $(this).addClass('isDrag').css({
												//        'position': 'absolute',
												//        'z-index': 1,
												//        'border-left': '1px solid #e6e6e6',
												//        'background-color': $(this).css('background-color'),
												//        'width': width + 1
												//    });
												//})
												//if ($totalTable.length > 0) {
												//    (isInFixed ? $fixedTotalTable : $totalTable).find('td[data-key="' + key + '"]').each(function () {
												//        $(this).after($(this).clone().css('visibility', 'hidden').attr('data-clone', ''));
												//        $(this).addClass('isDrag').css({
												//            'position': 'absolute',
												//            'z-index': 1,
												//            'background-color': $(this).parents('tr:eq(0)').css('background-color'),
												//            'width': width + 1
												//        });
												//    })
												//}
											}

											if (!isInFixed) {
												//非拖动固定列允许滚动条自滚动

												//记录当前左右边界的 x 坐标
												var $fixedL = $tableBox.children('.layui-table-fixed-l'),
													$fixedR = $tableBox.children('.layui-table-fixed-r')
												if ($fixedL.length != 0) {
													tableLx = $fixedL[0].getBoundingClientRect().right
												} else {
													tableLx = $tableBox[0].getBoundingClientRect().left
												}

												if ($fixedR.length != 0) {
													tableRx = $fixedR[0].getBoundingClientRect().left
												} else {
													tableRx = $tableBox[0].getBoundingClientRect().right
												}
											}
										}
										isDraging = true

										var x,
											y,
											i,
											j,
											tempCols,
											left = e.clientX - disX, // 计算当前被移动列左侧位置应该哪里
											$leftTh = $cloneHead.prev().prev(),
											hasLeftTh = $leftTh.length > 0,
											leftKey = hasLeftTh ? $leftTh.data('key').split('-') : [],
											$rightTh = $cloneHead.next().hasClass('layui-table-patch') ? [] : $cloneHead.next(),
											hasRightTh = $rightTh.length > 0,
											rightKey = hasRightTh ? $rightTh.data('key').split('-') : [],
											leftMove = hasLeftTh && $cloneHead.position().left - left > $leftTh.width() / 2.0,
											rightMove = hasRightTh && left - $cloneHead.position().left > $rightTh.width() / 2.0
										//moveDistince = Math.abs($cloneHead.position().left - left); //记录移动距离
										// 移动到左右两端、checbox/radio 固定列等停止移动
										if ($cloneHead.position().left - left > 0 ? !hasLeftTh || !!isFixed !== !!myTable.cols[leftKey[1]][leftKey[2]].fixed : !hasRightTh || !!isFixed !== !!myTable.cols[rightKey[1]][rightKey[2]].fixed) {
											$this.css('left', $cloneHead.position().left)
											//$tableBody.find('td[data-key="' + key + '"][data-clone]').each(function (e) {
											//    $(this).prev().css('left', $cloneHead.position().left);
											//})
											//if ($totalTable.length > 0) {
											//    $totalTable.find('td[data-key="' + key + '"][data-clone]').each(function (e) {
											//        $(this).prev().css('left', $cloneHead.position().left);
											//    })
											//}
											$tableBox.addClass('no-left-border')
											return
										}
										$this.css('left', left)

										//function corrMove(scrollMouseScale) {
										//    $thisTableBody.scrollLeft($thisTableBody.scrollLeft() + scrollMouseScale)
										//    $this.css('left', $this.position().left + scrollMouseScale);
										//    var isToLeft = scrollMouseScale < 0

										//    var offset = $this.offset(),
										//        cruxEs = _this.elementsFromPoint(isToLeft ? offset.left + 60:offset.left - 60, offset.top),
										//        cruxE;
										//    if (!!cruxEs && cruxEs.length > 0) {
										//        getTH()
										//    }
										//    if (!cruxE) {
										//        var cruxEs = _this.elementsFromPoint(e.clientX, e.clientY)
										//        if (!!cruxEs && cruxEs.length > 0) {
										//            getTH()
										//            if (!cruxE) {
										//                switch ('TD') {
										//                    case cruxEs[0].tagName:
										//                        cruxE = $tableHead.find('th[data-key="' + cruxEs[0].getAttribute('data-key') + '"]')[0]
										//                        break;
										//                    case cruxEs[1].tagName:
										//                        cruxE = $tableHead.find('th[data-key="' + cruxEs[1].getAttribute('data-key') + '"]')[0]
										//                        break;
										//                    case cruxEs[2].tagName:
										//                        cruxE = $tableHead.find('th[data-key="' + cruxEs[2].getAttribute('data-key') + '"]')[0]
										//                        break;
										//                }
										//            }
										//        }
										//    }
										//    if (!!cruxE && $(cruxE).parents('.layui-table-fixed').length === 0) {
										//        if (isToLeft) {
										//            $(cruxE).before($cloneHead)
										//        } else {
										//            $(cruxE).after($cloneHead)
										//        }

										//        $cloneHead.before($this)
										//    }
										//    lastClientX = e.clientX
										//    disX = e.clientX - $this.position().left // 重置鼠标距离被移动元素左侧的距离

										//    function getTH() {
										//        if (!!cruxEs[0] && cruxEs[0].tagName == 'TH' && cruxEs[0].getAttribute('data-field') != field && $(cruxEs[0]).parents('.layui-table-fixed').length === 0) {
										//            cruxE = cruxEs[0]
										//        } else if (!!cruxEs[1] && cruxEs[1].tagName == 'TH' && cruxEs[1].getAttribute('data-field') != field && $(cruxEs[1]).parents('.layui-table-fixed').length === 0) {
										//            cruxE = cruxEs[1]
										//        } else if (!!cruxEs[2] && cruxEs[2].tagName == 'TH' && cruxEs[2].getAttribute('data-field') != field && $(cruxEs[2]).parents('.layui-table-fixed').length === 0) {
										//            cruxE = cruxEs[2]
										//        } else if (!!cruxEs[3] && cruxEs[3].tagName == 'TH' && cruxEs[3].getAttribute('data-field') != field && $(cruxEs[3]).parents('.layui-table-fixed').length === 0) {
										//            cruxE = cruxEs[3]
										//        } else if (!!cruxEs[4] && cruxEs[4].tagName == 'TH' && cruxEs[4].getAttribute('data-field') != field && $(cruxEs[4]).parents('.layui-table-fixed').length === 0) {
										//            cruxE = cruxEs[4]
										//        } else if (!!cruxEs[5] && cruxEs[5].tagName == 'TH' && cruxEs[5].getAttribute('data-field') != field && $(cruxEs[5]).parents('.layui-table-fixed').length === 0) {
										//            cruxE = cruxEs[5]
										//        }

										//    }
										//}

										function corrMove(scrollMouseScale) {
											//移动事件
											var posLeft = $this.position().left + scrollMouseScale //拖动元素的 left 值
											isToLeft = scrollMouseScale < 0 //是否为向左拖动
											$thisTableBody.scrollLeft($thisTableBody.scrollLeft() + scrollMouseScale) //移动滚动条
											$this.css('left', posLeft) //重新定位 拖动元素
											var partWidth = fixedWidth,
												$cruxE,
												cruxEWidthCut = 0 //记录循环过的宽度, 拖动列下方的元素, table 左边缘到 $cruxE 中间的 宽度
											for (var i = 0, colsLength = colsWidthArr.length; i < colsLength; i++) {
												if (colsWidthArr[i].curColumn.hide) continue //跳过隐藏的元素
												var thWidth = !!colsWidthArr[i].curColumn.width ? Number(colsWidthArr[i].curColumn.width) : colsWidthArr[i].width //优先拿取 myTable 的宽度
												//console.log(myTable, i, colsWidthArr[i].curColumn.width, colsWidthArr[i].width, posLeft)
												partWidth += thWidth
												if (partWidth > posLeft) {
													$cruxE = colsWidthArr[i].thElem
													cruxEWidthCut = partWidth - thWidth + thWidth / 2
													break
												}
											}
											if (!!$cruxE && $cruxE.length > 0) {
												if (isToLeft) {
													//向左拖动
													if (posLeft > cruxEWidthCut) {
														$cruxE.after($cloneHead)
													} else {
														$cruxE.before($cloneHead)
													}
												} else {
													//向右拖动
													//if (posLeft > cruxEWidthCut) {
													//    var $nextColE = $cruxE.next()
													//    if ($nextColE.length > 0 && !myTable.cols[0][$nextColE.index()].fixed) {
													//        $nextColE.after($cloneHead)
													//    } else {
													//        $cruxE.after($cloneHead)
													//    }
													//} else {
													$cruxE.after($cloneHead)
													//}
												}
												$cloneHead.before($this)
											} else if (!$cruxE && !isToLeft) {
												//向右拖动定位不到下方元素则取最后一个
												if (!isToLeft) {
													$cruxE = colsWidthArr[colsWidthArr.length - 1].thElem
													$cruxE.after($cloneHead)
													$cloneHead.before($this)
												}
											}
											lastClientX = e.clientX //记录拖动后的鼠标坐标, 被卡住移动
											disX = e.clientX - $this.position().left // 重置鼠标距离被移动元素左侧的距离
										}

										//移动滚动条
										var $thisTableBody = $tableBox.children('.layui-table-body')
										var Loffset = tableLx - $this[0].getBoundingClientRect().left, //左固定列 - 移动列的距离
											Roffset = $this[0].getBoundingClientRect().right - tableRx //移动列的距离 - 右固定列
										if (Loffset > 1 && (e.clientX < lastClientX || lastClientX === -1) && !isInFixed) {
											var RmouseOffset = tableLx - e.clientX, //鼠标距离左固定列的距离
												scrollMouseScale = $thisTableBody.scrollLeft() / (RmouseOffset + 10) //本次应滚动的距离
											scrollMouseScale !== Infinity || (scrollMouseScale = 0)
											if (scrollMouseScale < 0) {
												corrMove(scrollMouseScale)
											}
										} else if (Roffset > 1 && e.clientX > lastClientX && !isInFixed) {
											var scrollSur = $thisTableBody[0].scrollWidth - $thisTableBody[0].clientWidth - $thisTableBody.scrollLeft(), //剩余滚动内容的宽度
												RmouseOffset = tableRx - e.clientX, //鼠标距离右固定列的距离
												scrollMouseScale = scrollSur / (RmouseOffset - 30) //本次应滚动的距离
											scrollMouseScale !== Infinity || (scrollMouseScale = 0)
											if (scrollMouseScale > 0) {
												corrMove(scrollMouseScale)
											}
										} else {
											$this.css('left', left)
											lastClientX = -1

											if (leftMove) {
												$cloneHead.after($leftTh)

												// 更新隐藏列顺序(表格筛选扩展)
												//$('#soul-columns' + tableId + '>li[data-value=' + field + ']').after($('#soul-columns' + tableId + '>li[data-value=' + field + ']').prev())

												// 更新配置信息
												//for (i = 0; i < myTable.cols.length; i++) {
												//    for (j = 0; j < myTable.cols[i].length; j++) {
												//        if (myTable.cols[i][j].key === curKey) {
												//            x = i;
												//            y = j;
												//            break;
												//        }
												//    }
												//    if (typeof x !== 'undefined' && typeof y !== 'undefined') {
												//        break;
												//    }
												//}
												//tempCols = myTable.cols[x][y - 1];
												//myTable.cols[x][y - 1] = myTable.cols[x][y];
												//myTable.cols[x][y] = tempCols;
												//if (!isNoCache) {
												//    localStorage.setItem(location.pathname + '#' + myTable.id, _this.deepStringify({ cols: myTable.cols, initSort: myTable.initSort}))
												//    //localStorage.setItem(location.pathname + '#' + myTable.id + ':cols', _this.deepStringify(myTable.cols))
												//}
											} else if (rightMove) {
												$cloneHead.prev().before($rightTh)

												// 更新隐藏列顺序(表格筛选扩展)
												//$('#soul-columns' + tableId + '>li[data-value=' + field + ']').before($('#soul-columns' + tableId + '>li[data-value=' + field + ']').next())

												// 更新配置信息
												//for (i = 0; i < myTable.cols.length; i++) {
												//    for (j = 0; j < myTable.cols[i].length; j++) {
												//        if (myTable.cols[i][j].key === curKey) {
												//            x = i;
												//            y = j;
												//            break;
												//        }
												//    }
												//    if (typeof x !== 'undefined' && typeof y !== 'undefined') {
												//        break;
												//    }
												//}
												//tempCols = myTable.cols[x][y + 1];
												//myTable.cols[x][y + 1] = myTable.cols[x][y];
												//myTable.cols[x][y] = tempCols;
												//if (!isNoCache) {
												//    localStorage.setItem(location.pathname + '#' + myTable.id, _this.deepStringify({ cols: myTable.cols, initSort: myTable.initSort }))
												//}
											}
										}

										//$tableBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
										//    $(this).prev().css('left', left);

										//    if (leftMove) {
										//        if ($(this).prev().prev().length !== 0) {
										//            $(this).after($(this).prev().prev());
										//        }
										//    } else if (rightMove) {
										//        if ($(this).next().length !== 0) {
										//            $(this).prev().before($(this).next());
										//        }
										//    }
										//})
										//if ($totalTable.length > 0) {
										//    $totalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
										//        $(this).prev().css('left', left);

										//        if (leftMove) {
										//            if ($(this).prev().prev().length !== 0) {
										//                $(this).after($(this).prev().prev());
										//            }
										//        } else if (rightMove) {
										//            if ($(this).next().length !== 0) {
										//                $(this).prev().before($(this).next());
										//            }
										//        }
										//    })
										//}

										if (!isNoHide) {
											/* 拖动隐藏列 */
											if (e.clientY - originTop > 60) {
												if ($('#column-remove').length === 0) {
													//$('body').append('<i id="column-remove" class="layui-red layui-icon layui-icon-delete"></i>')
													$('body').append(
														'<img id="column-remove" src="">'
													)
												}
												$('#column-remove').css({
													top: e.clientY - $('#column-remove').height() / 2,
													left: e.clientX - $('#column-remove').width() / 2,
													//'font-size': (e.clientY - originTop - 50) + 'px'
													width: e.clientY - originTop - 50 + 'px'
												})
												$('#column-remove').show()
											} else {
												$('#column-remove').hide()
											}
										}
									}
								})
								.on('mouseup', function () {
									$(document).unbind('selectstart')
									$('body').off('mousemove').off('mouseup')
									if (isStart && $cloneHead) {
										isStart = false
										if (isDraging) {
											if (curColumn.type !== 'checkbox') {
												$that.on('click', function (e) {
													e.stopPropagation()
												})
											}

											isDraging = false
											$tableBox.removeClass('no-left-border')
											$this.removeClass('isDrag').css({
												position: 'relative',
												'z-index': 'inherit',
												left: 'inherit',
												'border-left': 'inherit',
												width: 'inherit',
												'background-color': 'inherit'
											})
											$this.next().remove()
											var x,
												y,
												eqCol = $this.index(),
												isMove = false //cols索引1, cols索引2, 在 dom 中的 th index, 是否有移动
											//更新配置信息
											for (var i = 0, oneLength = myTable.cols.length; i < oneLength; i++) {
												for (var j = 0, twoLength = myTable.cols[i].length; j < twoLength; j++) {
													if (myTable.cols[i][j].key === curKey) {
														x = i
														y = j
														break
													}
												}
												if (typeof x !== 'undefined' && typeof y !== 'undefined') {
													break
												}
											}
											if (eqCol > y) {
												//往右移动
												myTable.cols[x].splice(eqCol + 1, 0, curColumn)
												myTable.cols[x].splice(y, 1)
												isMove = true
											} else if (eqCol < y) {
												//往左移动
												myTable.cols[x].splice(eqCol, 0, curColumn)
												myTable.cols[x].splice(y + 1, 1)
												isMove = true
											}
											if (isMove) {
												if (!isNoCache) {
													localStorage.setItem(location.pathname + '#' + myTable.id, _this.deepStringify({ cols: myTable.cols, initSort: myTable.initSort }))
												}
											}

											var prefKey = $this.prev().data('key')
											if (isFixed) {
												var $noFixedTh = $tableBox
													.children('.layui-table-header')
													.children('table')
													.find('th[data-key="' + key + '"]')
												if (prefKey) {
													$noFixedTh
														.parent()
														.children('th[data-key="' + prefKey + '"]')
														.after($noFixedTh)
												} else {
													if (isFixed === 'right') {
														if ($this.siblings().length > 0) {
															$tableBox
																.children('.layui-table-header')
																.children('table')
																.find('th[data-key="' + $this.next().data('key') + '"]')
																.prev()
																.after($noFixedTh)
														}
													} else {
														$noFixedTh.parent().prepend('<th class="layui-hide"></th>')
														$noFixedTh.parent().children('th:first').after($noFixedTh)
														$noFixedTh.parent().children('th:first').remove()
													}
												}
											}
											if (isSimple) {
												$tableBody.find('td[data-key="' + key + '"]').each(function () {
													if (prefKey) {
														$(this)
															.parent()
															.children('td[data-key="' + prefKey + '"]')
															.after($(this))
													} else {
														if (isFixed === 'right') {
															if ($this.siblings().length > 0) {
																var $preTd = $(this)
																	.parent()
																	.children('td[data-key="' + $this.next().data('key') + '"]')
																	.prev()
																if ($preTd.length > 0) {
																	$preTd.after($(this))
																} else {
																	$(this).parent().prepend('<td class="layui-hide"></td>')
																	$(this).parent().children('td:first').after($(this))
																	$(this).parent().children('td:first').remove()
																}
															}
														} else {
															$(this).parent().prepend('<td class="layui-hide"></td>')
															$(this).parent().children('td:first').after($(this))
															$(this).parent().children('td:first').remove()
														}
													}
												})
												if ($totalTable.length > 0) {
													$totalTable.find('td[data-key="' + key + '"]').each(function () {
														if (prefKey) {
															$(this)
																.parent()
																.children('td[data-key="' + prefKey + '"]')
																.after($(this))
														} else {
															if (isFixed === 'right') {
																var $preTd = $(this)
																	.parent()
																	.children('td[data-key="' + $this.next().data('key') + '"]')
																	.prev()
																if ($preTd.length > 0) {
																	$preTd.after($(this))
																} else {
																	$(this).parent().prepend('<td class="layui-hide"></td>')
																	$(this).parent().children('td:first').after($(this))
																	$(this).parent().children('td:first').remove()
																}
															} else {
																$(this).parent().prepend('<td class="layui-hide"></td>')
																$(this).parent().children('td:first').after($(this))
																$(this).parent().children('td:first').remove()
															}
														}
													})
												}
											} else if (isInFixed) {
												$noFixedBody.find('td[data-key="' + key + '"]').each(function () {
													if (prefKey) {
														$(this)
															.parent()
															.children('td[data-key="' + prefKey + '"]')
															.after($(this))
													} else {
														if (isFixed === 'right') {
															if ($this.siblings().length > 0) {
																var $preTd = $(this)
																	.parent()
																	.children('td[data-key="' + $this.next().data('key') + '"]')
																	.prev()
																if ($preTd.length > 0) {
																	$preTd.after($(this))
																} else {
																	$(this).parent().prepend('<td class="layui-hide"></td>')
																	$(this).parent().children('td:first').after($(this))
																	$(this).parent().children('td:first').remove()
																}
															}
														} else {
															$(this).parent().prepend('<td class="layui-hide"></td>')
															$(this).parent().children('td:first').after($(this))
															$(this).parent().children('td:first').remove()
														}
													}
												})
												//$fixedBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
												//    $(this).prev().removeClass('isDrag').css({
												//        'position': 'relative',
												//        'z-index': 'inherit',
												//        'left': 'inherit',
												//        'border-left': 'inherit',
												//        'width': 'inherit',
												//        'background-color': 'inherit'
												//    });
												//    $(this).remove();
												//});
												if ($totalTable.length > 0) {
													$noFixedTotalTable.find('td[data-key="' + key + '"]').each(function () {
														if (prefKey) {
															$(this)
																.parent()
																.children('td[data-key="' + prefKey + '"]')
																.after($(this))
														} else {
															if (isFixed === 'right') {
																var $preTd = $(this)
																	.parent()
																	.children('td[data-key="' + $this.next().data('key') + '"]')
																	.prev()
																if ($preTd.length > 0) {
																	$preTd.after($(this))
																} else {
																	$(this).parent().prepend('<td class="layui-hide"></td>')
																	$(this).parent().children('td:first').after($(this))
																	$(this).parent().children('td:first').remove()
																}
															} else {
																$(this).parent().prepend('<td class="layui-hide"></td>')
																$(this).parent().children('td:first').after($(this))
																$(this).parent().children('td:first').remove()
															}
														}
													})
													//$fixedTotalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
													//    $(this).prev().removeClass('isDrag').css({
													//        'position': 'relative',
													//        'z-index': 'inherit',
													//        'left': 'inherit',
													//        'width': 'inherit',
													//        'background-color': 'inherit'
													//    });
													//    $(this).remove();
													//});
												}
											}
											//else {
											//    $tableBody.find('td[data-key="' + key + '"][data-clone]').each(function () {
											//        $(this).prev().removeClass('isDrag').css({
											//            'position': 'relative',
											//            'z-index': 'inherit',
											//            'left': 'inherit',
											//            'width': 'inherit',
											//            'background-color': 'inherit'
											//        });
											//        $(this).remove();
											//    });
											//    if ($totalTable.length > 0) {
											//        $totalTable.find('td[data-key="' + key + '"][data-clone]').each(function () {
											//            $(this).prev().removeClass('isDrag').css({
											//                'position': 'relative',
											//                'z-index': 'inherit',
											//                'left': 'inherit',
											//                'width': 'inherit',
											//                'background-color': 'inherit'
											//            });
											//            $(this).remove();
											//        });
											//    }
											//}

											$cloneHead = null

											// 处理 toolbar 事件
											if (toolbar) {
												//if ($dragBar.children('.active').length > 0 && $dragBar.children('.active').attr('data-type') !== $dragBar.attr('data-type')) {
												//    var targetFix = $dragBar.children('.active').attr('data-type'),
												//        i, j, curPos, targetPos;
												//    for (i = 0; i < myTable.cols.length; i++) {
												//        for (j = 0; j < myTable.cols[i].length; j++) {
												//            if (targetFix === 'right' || (targetFix === 'none' && $dragBar.attr('data-type') === 'right')) {
												//                if (typeof targetPos === 'undefined') {
												//                    if (myTable.cols[i][j].fixed === 'right') {
												//                        targetPos = { x: i, y: j };
												//                    } else if (j === myTable.cols[i].length - 1) {
												//                        targetPos = { x: i, y: j + 1 };
												//                    }
												//                }
												//            } else {
												//                if (typeof targetPos === 'undefined' && (!myTable.cols[i][j].fixed || myTable.cols[i][j].fixed === 'right')) {
												//                    targetPos = { x: i, y: j };
												//                }
												//            }
												//            if (myTable.cols[i][j].key === curKey) {
												//                curPos = { x: i, y: j };
												//            }
												//        }
												//    }
												//    curColumn['fixed'] = targetFix === 'none' ? false : targetFix;
												//    if (curPos.y !== targetPos.y) {
												//        myTable.cols[curPos.x].splice(curPos.y, 1);
												//        if (curPos.y < targetPos.y) {
												//            targetPos.y -= 1
												//        }
												//        myTable.cols[targetPos.x].splice(targetPos.y, 0, curColumn)
												//        if (!isNoCache) {
												//            localStorage.setItem(location.pathname + '#' + myTable.id, _this.deepStringify({ cols: myTable.cols, initSort: myTable.initSort }))
												//        }
												//    }
												//    table.reload(tableId)
												//}
												//$dragBar.removeClass('active')
											}
										} else {
											$that.unbind('click')
										}
										if ($('#column-remove').is(':visible')) {
											$tableHead.find('thead>tr>th[data-key=' + key + ']').addClass(HIDE)
											$tableBody.find('tbody>tr>td[data-key="' + key + '"]').addClass(HIDE)
											$totalTable.find('tbody>tr>td[data-key="' + key + '"]').addClass(HIDE)
											// 同步配置
											curColumn['hide'] = true
											if (!isNoCache) {
												localStorage.setItem(location.pathname + '#' + myTable.id, _this.deepStringify({ cols: myTable.cols, initSort: myTable.initSort }))
											}
											// 更新下拉隐藏
											//$('#soul-columns' + tableId).find('li[data-value="' + field + '"]>input').prop('checked', false);
										}
										$('#column-remove').hide()
									}
								})
						})
				})
			}
		},
		//工具栏列显示隐藏
		toolCols: function (myTable) {
			var _this = this
			var ID = !!myTable.id ? '#' + myTable.id : myTable.elem,
				$elem = $.type(myTable.elem) === 'string' ? $(ID) : myTable.elem

			$elem
				.next()
				.find('[lay-event="LAYTABLE_COLS"]')
				.click(function () {
					var $this = $(this)
					setTimeout(function () {
						$this.find('li').on('click', function () {
							var $checkInput = $(this).find('[lay-filter="LAY_TABLE_TOOL_COLS"]')
							var key = $checkInput.data('key')
							keyArray = key.split('-')
							myTable.cols[keyArray[0]][keyArray[1]]['hide'] = !$checkInput[0].checked
							if (isNoCache) return
							localStorage.setItem(location.pathname + ID, _this.deepStringify({ cols: myTable.cols, initSort: myTable.initSort }))
						})
					}, 100)
				})
		},
		//行默认排序
		initSort: function (myTable) {
			if (isNoCache) return
			var _this = this
			var ID = !!myTable.id ? '#' + myTable.id : myTable.elem
			table.on('sort(' + ID.replace('#', '') + ')', function (obj) {
				//注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
				myTable.initSort = {
					field: obj.field, //排序字段，对应 cols 设定的各字段名
					type: obj.type //排序方式  asc: 升序、desc: 降序、null: 默认排序
				}
				localStorage.setItem(location.pathname + ID, _this.deepStringify({ cols: myTable.cols, initSort: myTable.initSort }))
			})
		},
		//保存本地
		fixTableRemember: function (myTable, dict) {
			if (isNoCache) return
			var ID = !!myTable.id ? '#' + myTable.id : myTable.elem
			if (dict && dict.rule) {
				var keyArray = dict.rule.selectorText.split('-')
				myTable.cols[keyArray[3]][keyArray[4]].width = dict.rule.style.width.replace('px', '')
			}
			localStorage.setItem(location.pathname + ID, this.deepStringify({ cols: myTable.cols, initSort: myTable.initSort }))
		},
		//上传缓存
		uploadTableCache: function (obj, _this) {
			var tableCacheUrl = location.pathname + '#' + obj.config.id,
				tableCache = localStorage.getItem(tableCacheUrl)
			if (!tableCache) {
				timemsg.open('本地缓存为空，上传个性化设置失败！')
				return
			}
			// 保存表格每页的数量
			if (tableCache) {
				let add = _this.deepParse(tableCache)
				add['limit'] = obj.config.limit
				tableCache = _this.deepStringify(add)
			}

			$.ajax({
				url: '/api/UserConfig',
				type: 'post',
				data: {
					AccountID: top.layui.AccountId,
					ConfigKey: tableCacheUrl,
					ConfigValue: tableCache
				},
				success: function (d) {
					timemsg.open('保存个性化设置' + d.message)
				},
				error: function () {
					timemsg.open('上传个性化设置失败！')
				}
			})
		},
		//下载缓存
		downTableCache: function (obj, _this, myTable) {
			var tableCacheUrl = location.pathname + '#' + obj.config.id

			$.ajax({
				url: '/api/UserConfig',
				type: 'get',
				data: {
					AccountID: top.layui.AccountId,
					ConfigKey: tableCacheUrl
				},
				success: function (d) {
					var tableCache = _this.deepParse(d.data.ConfigValue)

					if (!!tableCache.cols && myTable.cols[0].length != tableCache.cols[0].length) {
						//判断简单列的长度和下载的是否相同,相同则使用服务器列排序
						timemsg.open('个性化设置列与本地列长度不同，取消应用')
						return
					}

					timemsg.open('下载个性化设置' + d.message)
					localStorage.setItem(tableCacheUrl, d.data.ConfigValue)

					!tableCache.cols || (myTable.cols = tableCache.cols)
					!tableCache.initSort || (myTable.initSort = tableCache.initSort)
					!myTable.page || (myTable.page.limit = tableCache.limit) // 设置每页的数量
					table.render(myTable)
				},
				error: function () {
					timemsg.open('下载个性化设置失败！')
				}
			})
		},
		//清除本地缓存
		clearTableCache: function (obj) {
			var ele = layer.confirm('确认 清除列表个性化 吗?', { icon: 3, title: '确认信息' }, function (index) {
				localStorage.removeItem(location.pathname + '#' + obj.config.id)
				timemsg.open('清除个性化设置成功！')

				layer.close(index)
			})
			setTimeout(function () {
				var ele_ = $('.layui-layer.layui-layer-dialog > .layui-layer-btn.layui-layer-btn- a.layui-layer-btn0')
				if (ele_.length > 0) {
					ele_.attr('href', '#_') // a标签没有href属性，不能获取到焦点，防止返回到页面顶部
					ele_.eq(0).focus()
				}
			}, 100)
		},
		deepParse: function (str) {
			var JSON_SERIALIZE_FIX = {
				PREFIX: '[[JSON_FUN_PREFIX_',
				SUFFIX: '_JSON_FUN_SUFFIX]]'
			}
			return (
				JSON.parse(str, function (key, value) {
					if (typeof value === 'string' && value.indexOf(JSON_SERIALIZE_FIX.SUFFIX) > 0 && value.indexOf(JSON_SERIALIZE_FIX.PREFIX) === 0) {
						return eval('(' + value.replace(JSON_SERIALIZE_FIX.PREFIX, '').replace(JSON_SERIALIZE_FIX.SUFFIX, '') + ')')
					}
					return value
				}) || {}
			)
		},
		deepStringify: function (obj) {
			var JSON_SERIALIZE_FIX = {
				PREFIX: '[[JSON_FUN_PREFIX_',
				SUFFIX: '_JSON_FUN_SUFFIX]]'
			}
			return JSON.stringify(obj, function (key, value) {
				if (typeof value === 'function') {
					return JSON_SERIALIZE_FIX.PREFIX + value.toString() + JSON_SERIALIZE_FIX.SUFFIX
				}
				return value
			})
		},
		elementsFromPoint: function (X, Y) {
			if (!!document.elementsFromPoint) {
				return document.elementsFromPoint(X, Y)
			} else {
				return document.msElementsFromPoint(X, Y)
			}
		},
		// 作用：在表格上面新增一个按钮，用于控制表格工具栏的显示和隐藏。
		toolsDisplay: function (myTable) {
			var ID = !!myTable.id ? '#' + myTable.id : myTable.elem,
				$elem = $.type(myTable.elem) === 'string' ? $(ID) : myTable.elem
			var already = $('#test-table-reload').prev().find('.form-lable.css_dindex').find('#toolsDisplay')
			if ($elem.prev().find('.form-lable.css_dindex').length == 0) return // 如果没有自定义的搜索栏，则退出改方法；
			if (already.length !== 0) already.remove()
			var html = `
                <div type="button" class="layui-btn layui-btn-sm layui-btn-primary" id="toolsDisplay" title="显隐表格工具栏" style="display: inline-block;position: absolute;right: 4px;margin: 0;padding: 0 6px; height: 25px; line-height: 25px;">
                <i class="layui-icon layui-icon-down" style="margin: 0;"></i>
                </div>`
			$(html).appendTo($elem.prev().find('.form-lable.css_dindex'))
			var tag = $elem.next().find('.layui-table-tool')
			tag.addClass('forceTable-toolHide')
			$('#toolsDisplay').click(function () {
				var _this = this
				if (tag.hasClass('forceTable-toolHide')) {
					tag.removeClass('forceTable-toolHide')
					$(_this).find('i').attr('class', 'layui-icon layui-icon-up')
				} else {
					tag.addClass('forceTable-toolHide')
					$(_this).find('i').attr('class', 'layui-icon layui-icon-down')
				}
				/* if (tag.css("display") !== "none") {
                    tag.hide()
                    $(_this).find('i').attr("class", "layui-icon layui-icon-down")
                } else{
                    tag.show()
                    $(_this).find('i').attr("class", "layui-icon layui-icon-up")
                } */
				table.resize(ID) //刷新表格尺寸
				if (window.isRuniframeAuto) iframe_height() //如果页面开启 iframe 自动高度
			})
		},
		// 排除所有页面中不需要显示给用户的列
		// excludeData:这是要自定义排除那些列，自由传入。
		exclude: function (myTable, excludeData) {
			var excludeArr = excludeData ? excludeData : [] // 这里是要排除的列名数组。
			var tagArr = []
			tagArr = myTable.cols[0].filter(function (currentValue, indedx, arr) {
				return !!currentValue.fixed ? true : !(currentValue.field && excludeArr.indexOf(currentValue.field) !== -1)
			})
			myTable.cols[0] = tagArr
		}
	}
	// 输出
	exports('forceTable', mod)
})
